﻿#include "dlgmain.h"
#include "ui_dlgmain.h"

#include <QDebug>

DlgMain::DlgMain(QWidget *parent) :
    QDialog(parent),
    ui(new Ui::DlgMain)
{
    ui->setupUi(this);

    //去掉窗口右上角的问号
    Qt::WindowFlags flags = this->windowFlags();
    flags |= Qt::WindowMinimizeButtonHint;
    flags &= ~Qt::WindowCloseButtonHint;
    this->setWindowFlags(flags);
    this->setFixedSize(320,251);

    // 1. 设置当前运行路径
    strRootDir = QCoreApplication::applicationDirPath();
    QDir::setCurrent(strRootDir);

    // 2. 托盘图标
    m_pSystemTray = new QSystemTrayIcon(this);
    m_pSystemTray->setToolTip(this->windowTitle());
    m_pSystemTray->setIcon(this->windowIcon());
    m_pSystemTray->show();
    connect(m_pSystemTray, SIGNAL(activated(QSystemTrayIcon::ActivationReason)), this, SLOT(trayicon_activated(QSystemTrayIcon::ActivationReason)));

    nIndex = 0;
    nFileCount = 0;
    m_bIsExtractSuccess = false;
    m_prTimer = new QTimer;
    connect(m_prTimer,SIGNAL(timeout()),this,SLOT(slot_checkUpdate()));
    m_prTimer->start(5000);

    init();
}

DlgMain::~DlgMain()
{
    delete ui;
}


void DlgMain::init()
{

    pr_setting = new QSettings("./Config/Update.ini", QSettings::IniFormat);
    pr_setting->setIniCodec("UTF-8");

    m_strUpdatePath = pr_setting->value("Path/UpdatePath").toString();
    zipFilePath = QString("%1/update.zip").arg(m_strUpdatePath);
    m_strTmpPath = QString("%1/update").arg(m_strUpdatePath);
    qDebug()<<"UpdatePath:"<<m_strUpdatePath;

    m_pProcCmd = new QProcess();
    m_pProcCmd->setWorkingDirectory(strRootDir);
    //m_pProcCmd->setStandardOutputFile("error.log");
    m_pProcCmd->start("cmd");

    p_CopyFileWorker = new TMCopyFileWorker;
    QThread *myThread = new QThread;
    p_CopyFileWorker->moveToThread(myThread);
    myThread->start();
    connect(this,SIGNAL(sig_extractDir(QString,QString)),p_CopyFileWorker,SLOT(slot_extractDir(QString,QString)));
    connect(p_CopyFileWorker,SIGNAL(sig_extractDirSuccess(QStringList)),this,SLOT(slot_extractDirSuccess(QStringList)));
    connect(this,SIGNAL(sig_copyDir(QString,QString)),p_CopyFileWorker,SLOT(slot_copyDir(QString,QString)),Qt::QueuedConnection);
    connect(p_CopyFileWorker,SIGNAL(sig_updateProgressBar()),this,SLOT(slot_updateProgressBar()));

    pDir = new QDir;
    if(!pDir->exists(m_strUpdatePath)){
        pDir->mkdir(m_strUpdatePath);
    }

    ui->progressBar->setValue(0);
    ui->progressBar->hide();
    ui->label->setText(QString::fromLocal8Bit("监控升级中..."));
}

void DlgMain::slot_checkUpdate()
{

    QFile file(zipFilePath);
    if(file.exists() && !m_bIsExtractSuccess){
        this->show();
        ui->progressBar->show();
        ui->label->setText(QString::fromLocal8Bit("程序升级中..."));
        m_pProcCmd->write("call closeAll.bat\r\n");

        m_bIsExtractSuccess = true;
        emit sig_extractDir(zipFilePath,m_strUpdatePath);
    }
}

qint64 DlgMain::getFolderSize(QString folder)
{
    QDir dir(folder);
    if (!dir.exists())
        return 0;
    qint64 totalsize = 0;
    QFileInfoList list = dir.entryInfoList(QDir::Dirs | QDir::Files | QDir::NoDotAndDotDot);
    foreach(QFileInfo fileInfo, list){
        if (fileInfo.isFile())
            totalsize += 1;
        else if(fileInfo.isDir())
            totalsize += getFolderSize(fileInfo.absoluteFilePath());

    }
    return totalsize;
}

void DlgMain::checkDirIsExist(QString strDirName)
{
    strDirPath = QString("D:/%1").arg(strDirName);
    QDir dir(strDirPath);
    if(dir.exists()){
        removeFolderContent(strDirPath);
    }else{
        dir.mkpath(strDirPath);
    }
}

void DlgMain::slot_extractDirSuccess(QStringList list)
{
    //qDebug()<<"list"<<list;
    pDir->remove(zipFilePath);
    nFileCount = getFolderSize(m_strTmpPath);
    if(nFileCount <= 0){
        m_bIsExtractSuccess = false;
        return;
    }

    qDebug()<<"nFileCount:"<<nFileCount;
    ui->progressBar->setRange(0,nFileCount);
    QDir m_Dir(m_strTmpPath);
    fileList = m_Dir.entryInfoList(QDir::Dirs | QDir::Files | QDir::NoDotAndDotDot);

    qDebug()<<"fileList"<<fileList.size();
    foreach(QFileInfo fileInfo, fileList){
        qDebug()<<"fileInfo:"<<fileInfo.filePath()<<fileInfo.fileName()<<fileInfo.baseName();
        if(fileInfo.isDir()){
            checkDirIsExist(fileInfo.fileName());
            emit sig_copyDir(fileInfo.filePath(),strDirPath);
        }
        if(fileInfo.isFile()){
            QDir dir(m_strUpdatePath);
            if(dir.exists(fileInfo.fileName())){
                dir.remove(fileInfo.fileName());
            }
            QFile::copy(fileInfo.filePath(),QString("%1/%2").arg(m_strUpdatePath).arg(fileInfo.fileName()));
        }
    }




}

void DlgMain::slot_updateProgressBar()
{
    nIndex++;
    qDebug()<<"file count:"<<nIndex;

    if(nIndex < nFileCount-1){
        ui->progressBar->setValue(nIndex);
    }
    else
    {
        ui->progressBar->setValue(nFileCount);
        nIndex = 0;
        m_bIsExtractSuccess = false;
        fileList.clear();

        removeFolderContent(m_strTmpPath);
        pDir->rmdir(m_strTmpPath);

        ui->label->setText(QString::fromLocal8Bit("程序升级完成，尝试重启电脑..."));
        ui->progressBar->hide();
        m_pProcCmd->write("shutdown -r -f -t 3\r\n");
    }
}


//删除非空文件夹
bool DlgMain::removeFolderContent(const QString &folderDir)
{
    QDir dir(folderDir);
    QFileInfoList fileList;
    QFileInfo curFile;
    if(!dir.exists()){//文件不存在，则返回false
        return false;
    }
    fileList=dir.entryInfoList(QDir::Dirs|QDir::Files
                               |QDir::Readable|QDir::Writable
                               |QDir::Hidden|QDir::NoDotAndDotDot
                               ,QDir::Name);
    while(fileList.size()>0)
    {
        int infoNum=fileList.size();
        for(int i=infoNum-1;i>=0;i--)
        {
            curFile=fileList[i];
            if(curFile.isFile())//如果是文件，删除文件
            {
                QFile fileTemp(curFile.filePath());
                fileTemp.remove();
                fileList.removeAt(i);
            }
            if(curFile.isDir())//如果是文件夹
            {
                QDir dirTemp(curFile.filePath());
                QFileInfoList fileList1=dirTemp.entryInfoList(QDir::Dirs|QDir::Files
                                                              |QDir::Readable|QDir::Writable
                                                              |QDir::Hidden|QDir::NoDotAndDotDot
                                                              ,QDir::Name);
                if(fileList1.size()==0)//下层没有文件或文件夹
                {
                    dirTemp.rmdir(".");
                    fileList.removeAt(i);
                }
                else//下层有文件夹或文件
                {
                    for(int j=0;j<fileList1.size();j++)
                    {
                        if(!(fileList.contains(fileList1[j])))
                            fileList.append(fileList1[j]);
                    }
                }
            }
        }
    }
    return true;
}

void DlgMain::trayicon_activated(QSystemTrayIcon::ActivationReason reason)
{
    if( reason == QSystemTrayIcon::DoubleClick || reason == QSystemTrayIcon::Context ){
        if( this->isVisible() ){
            this->hide();
            //托盘显示提示信息
            m_pSystemTray->showMessage(QString::fromLocal8Bit("Tami.RobotCore信息:"), QString::fromLocal8Bit("窗口已经隐藏..."), QSystemTrayIcon::Information, 1000);
        }else{
            this->show();
            m_pSystemTray->showMessage(QString::fromLocal8Bit("Tami.RobotCore信息:"), QString::fromLocal8Bit("窗口已经显示..."), QSystemTrayIcon::Information, 1000);
        }
    }

}

void DlgMain::on_btn_hide_clicked()
{
    this->hide();
}

void DlgMain::on_btn_exit_clicked()
{
    this->close();
}
